package com.ld.realm;

import com.ld.entity.Staff;
import com.ld.service.UserService;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;
@Slf4j
public class StaffRealm extends AuthorizingRealm {

    @Resource(name = "userService")
    private UserService userServiceImpl;

    /**测试用户:
     * staff_id 1： Mike 密码123  1号店
     * 拥有角色[SuperAdmin, Admin, Manager, Clerk]
     * staff_id 3： ld 密码123   1号店
     * 拥有角色[account, Manager, Clerk]
     *
     * staff_id 5： jet 密码123   1号店经理
     * 拥有角色[Manager, Clerk]
     * staff_id 6： gl 密码123  1号店店员
     * 拥有角色[Clerk]
     *
     * staff_id 2： Jon 密码123   2号店经理
     * 拥有角色[Manager, Clerk]
     * staff_id 4： dog 密码123  2号店店员
     * 拥有角色[Clerk]
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用了授权方法!!!!!");
        //从session中获取当前用户的角色列表
        Session session = SecurityUtils.getSubject().getSession();
        Staff loginUser =(Staff) session.getAttribute("loginUser");
        if (loginUser!=null){
        List<String> userRoleType = loginUser.getRoleType();
        SimpleAuthorizationInfo sa = new SimpleAuthorizationInfo();
        sa.addRoles(userRoleType);
        return sa;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("调用了认证方法!!!!!");
        //在token中获取账号(前端传来的)
        String userName = (String) token.getPrincipal();
        Staff staff = userServiceImpl.staffLogin(userName);
        if (staff != null && userName.equals(staff.getUserName())) {
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute("loginUser",staff);

            //返回IncorrectCredentialsException 则是密码错误
            return new SimpleAuthenticationInfo(userName,
                    staff.getPassWord(), ByteSource.Util.bytes(staff.getSalt()),
                    this.getName());
        }
        //返回null则异常是UnknownAccountException,账号错误
        return null;
    }
}
